<template>
	<view class="container">
		<view class="left-bottom-sign"></view>
		<view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view>
		<view class="right-top-sign"></view>

		<view class="wrapper">
			<view class="left-top-sign">LOGIN</view>
			<view class="welcome">
				欢迎登录酒商城
			</view>

			<view class="login-tips">
				<text class="tips-text">请使用微信授权登录</text>
			</view>

			<!-- 微信小程序授权登录按钮 -->
			<button class="wx-login-btn" @click="wxLogin" :disabled="logining">
				<image class="wx-icon" src="/static/wx-icon.png" mode="aspectFit"></image>
				<text>{{ logining ? '登录中...' : '微信授权登录' }}</text>
			</button>

			<view class="user-agreement">
				<text>登录即表示同意</text>
				<text class="link">《用户协议》</text>
				<text>和</text>
				<text class="link">《隐私政策》</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex';
	import {
		wxMiniLogin,
		memberInfo
	} from '@/api/member.js';

	export default {
		data() {
			return {
				logining: false
			}
		},
		methods: {
			...mapMutations(['login']),

			navBack() {
				uni.navigateBack();
			},

			/**
			 * 微信小程序授权登录
			 */
			async wxLogin() {
				this.logining = true;

				try {
					// 1. 调用 wx.login 获取 code
					const loginRes = await this.wxLoginAsync();
					const code = loginRes.code;

					if (!code) {
						uni.showToast({
							title: '获取登录凭证失败',
							icon: 'none'
						});
						this.logining = false;
						return;
					}

					console.log('获取到code:', code);

					// 2. 获取用户信息（微信小程序新版本需要用户授权）
					let nickName = '';
					let avatarUrl = '';

					try {
						// 注意：微信小程序基础库 2.27.1 以上需要使用 wx.getUserProfile
						const userRes = await this.getUserProfileAsync();
						nickName = userRes.userInfo.nickName;
						avatarUrl = userRes.userInfo.avatarUrl;
						console.log('获取用户信息成功:', nickName);
					} catch (e) {
						// 用户拒绝授权，使用默认信息
						console.log('用户未授权获取信息，使用默认信息');
					}

					// 3. 发送到后端登录
					const response = await wxMiniLogin({
						code: code,
						nickName: nickName,
						avatarUrl: avatarUrl
					});

					// 4. 登录成功，保存token和用户信息
					if (response.code === 200 && response.data) {
						const {
							token,
							tokenHead,
							userInfo
						} = response.data;

						// 保存token
						uni.setStorageSync('token', tokenHead + token);

						// 保存用户信息到vuex
						this.login(userInfo);

						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});

						// 延迟返回
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: response.message || '登录失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('登录失败:', error);
					uni.showToast({
						title: error.message || '登录失败，请重试',
						icon: 'none'
					});
				} finally {
					this.logining = false;
				}
			},

			/**
			 * wx.login Promise化
			 */
			wxLoginAsync() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: (res) => resolve(res),
						fail: (err) => reject(err)
					});
				});
			},

			/**
			 * wx.getUserProfile Promise化
			 */
			getUserProfileAsync() {
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						desc: '用于完善用户资料',
						success: (res) => resolve(res),
						fail: (err) => reject(err)
					});
				});
			}
		}
	}
</script>

<style lang='scss'>
	page {
		background: #fff;
	}

	.container {
		padding-top: 115px;
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background: #fff;
	}

	.wrapper {
		position: relative;
		z-index: 90;
		background: #fff;
		padding-bottom: 40upx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.back-btn {
		position: absolute;
		left: 40upx;
		z-index: 9999;
		padding-top: var(--status-bar-height);
		top: 40upx;
		font-size: 40upx;
		color: $font-color-dark;
	}

	.left-top-sign {
		font-size: 120upx;
		color: $page-color-base;
		position: relative;
		left: -16upx;
		align-self: flex-start;
	}

	.right-top-sign {
		position: absolute;
		top: 80upx;
		right: -30upx;
		z-index: 95;

		&:before,
		&:after {
			display: block;
			content: "";
			width: 400upx;
			height: 80upx;
			background: #b4f3e2;
		}

		&:before {
			transform: rotate(50deg);
			border-radius: 0 50px 0 0;
		}

		&:after {
			position: absolute;
			right: -198upx;
			top: 0;
			transform: rotate(-50deg);
			border-radius: 50px 0 0 0;
		}
	}

	.left-bottom-sign {
		position: absolute;
		left: -270upx;
		bottom: -320upx;
		border: 100upx solid #d0d1fd;
		border-radius: 50%;
		padding: 180upx;
	}

	.welcome {
		position: relative;
		left: 0;
		top: -90upx;
		font-size: 46upx;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0, 0, 0, .3);
		text-align: center;
	}

	.login-tips {
		margin-top: 40upx;
		margin-bottom: 60upx;

		.tips-text {
			font-size: 28upx;
			color: $font-color-light;
		}
	}

	.wx-login-btn {
		width: 630upx;
		height: 88upx;
		line-height: 88upx;
		border-radius: 50px;
		margin-top: 40upx;
		background: #07c160;
		color: #fff;
		font-size: $font-lg;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8upx 20upx rgba(7, 193, 96, 0.3);

		&:after {
			border-radius: 100px;
			border: none;
		}

		.wx-icon {
			width: 48upx;
			height: 48upx;
			margin-right: 16upx;
		}
	}

	.user-agreement {
		margin-top: 80upx;
		font-size: 24upx;
		color: $font-color-light;
		text-align: center;

		.link {
			color: $uni-color-primary;
		}
	}
</style>
